package com.zj.juc.study.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName AtomicFieldUpdaterDemo
 * @Description 对象的属性修改原子类demo
 * @createTime 2025年01月03日 20:29
 */
public class AtomicFieldUpdaterDemo {

    public static final Integer SIZE=50;


    public static void main(String[] args) {

        AtomicIntegerFieldUpdater<BankCount> updater = AtomicIntegerFieldUpdater.newUpdater(BankCount.class,"money");

        BankCount bankCount = new BankCount();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 0; i < SIZE; i++) {
            new Thread(()->{
                try {
                    for (int j = 0; j < 1000; j++) {
                        updater.getAndIncrement(bankCount);
                    }
                } finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(bankCount.money);
    }
}


class BankCount{
    String blankName = "CCB";

    //必须是public volatile int
    public volatile int money = 0;

    public  void  add(){
        money++;
    }
}